<template>
  <div>
    <el-row>
      <el-col style="margin-top: 10px">
        <el-input
          v-model="search"
          style="width: 240px"
          placeholder="请输入用户名"
        />
        <el-button style="margin-left: 20px" type="primary">搜索</el-button>
        <el-button style="margin-left: 20px" type="primary" @click="add"
          >添加用户</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="Name"
            label="用户名"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Phone"
            label="手机号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Age"
            label="年龄"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Sex"
            label="性别"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                size="small"
                @click="
                  info(scope.row);
                  dialogVisible = true;
                "
                >详情</el-button
              > -->
              <el-button
                link
                type="primary"
                size="small"
                style="color: red"
                @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        v-model="dialogVisible_add"
        title="新增用户"
        width="50%"
        :before-close="handleClose"
      >
        <el-form
          :model="form"
          label-position="right"
          ref="ruleFormRef"
          :rules="rules"
        >
          <el-form-item label="姓名:" label-width="100px" prop="name">
            <el-input
              v-model="form.name"
              style="width: 200px"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="年龄:" label-width="100px" prop="age">
            <el-input
              v-model.number="form.age"
              type="number"
              style="width: 200px"
              placeholder="请输入年龄"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别:" label-width="100px" prop="sex">
            <el-select
              v-model="form.sex"
              placeholder="请选择性别"
              size="large"
              style="width: 200px"
            >
              <el-option
                v-for="item in options_sex"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号:" label-width="100px" prop="phone">
            <el-input
              v-model.number="form.phone"
              style="width: 200px"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份:" label-width="100px" prop="roleid">
            <el-select
              v-model="form.roleid"
              placeholder="请选择性别"
              size="large"
              style="width: 200px"
            >
              <el-option
                v-for="item in options_roleid_1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                v-if="type == 1"
              />
              <el-option
                v-for="item in options_roleid_2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                v-if="type == 2"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账号:" label-width="100px" prop="account">
            <el-input
              v-model="form.account"
              style="width: 200px"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码:" label-width="100px" prop="password">
            <el-input
              v-model="form.password"
              style="width: 200px"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-button
            style="width: 20%; margin-left: 20%"
            type="primary"
            @click="baocun_add(ruleFormRef)"
            >保存</el-button
          >
        </el-form>
      </el-dialog>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import apiService from "@/services/apiService";
import { conversionUtcDate, base64ToExcelAndDownload } from "@/utils/auth";
import { v4 as uuidv4 } from "uuid";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
const UserStore = useUserStoreHook();

//表格数据
const Data = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const search = ref("");
//分页查询所有用户
const GetList = () => {
  const params = {
    msgid: "GetAllUsers",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      Data.value = [];
      Data.value.push(...res.data.body.users);
      Total.value = res.data.body.totalUsers;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

//新增用户
const dialogVisible_add = ref(false);
const ruleFormRef = ref<FormInstance>();
const form = ref<any>({
  name: "",
  age: "",
  sex: "",
  phone: "",
  roleid: "",
  account: "",
  password: ""
});
const options_sex = [
  { value: "男", label: "男" },
  { value: "女", label: "女" }
];
const options_roleid_1 = [
  { value: "1", label: "管理员" },
  { value: "2", label: "普通用户" },
  { value: "5", label: "第一监护人" }
];
const options_roleid_2 = [
  { value: "2", label: "普通用户" },
  { value: "5", label: "第一监护人" }
];
const rules = reactive<FormRules<any>>({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  sex: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change"
    }
  ],
  phone: [
    {
      required: true,
      message: "请填写手机号",
      trigger: "blur"
    }
  ],
  roleid: [{ required: true, message: "请选择身份", trigger: "change" }],
  account: [{ required: true, message: "请填写账号", trigger: "blur" }],
  password: [{ required: true, message: "请填写密码", trigger: "blur" }]
});
const add = () => {
  dialogVisible_add.value = true;
};
const baocun_add = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("输出!");
      // @ts-ignore
      console.log("当前用户身份", UserStore.type);
      if (form.value.roleid == 1) {
        //添加管理员，调用超级管理员接口
        const params = {
          msgid: "AddAdminUser",
          token: getToken().accessToken,
          seq: uuidv4(),
          body: {
            name: form.value.name,
            age: form.value.age,
            sex: form.value.sex,
            phone: form.value.phone,
            roleid: form.value.roleid,
            account: form.value.account,
            password: form.value.password,
            openid: ""
          }
        };
        apiService
          .post("", params)
          .then((res: any) => {
            // 使用 any 类型断言
            console.log(res.data);
             if (res.data.code == 200) {
              dialogVisible_add.value = false;
              form.value = [];
              message("管理员新增完成", { type: "success" });
               GetList();
            } else if (res.data.code == 504) {
              message("用户已存在", { type: "warning" });
            }
          })
          .catch(error => {
            console.error("Error fetching data:", error);
          });
      } else {
        //添加用户
        const params = {
          msgid: "InsertUser",
          token: getToken().accessToken,
          seq: uuidv4(),
          body: {
            name: form.value.name,
            age: form.value.age,
            sex: form.value.sex,
            phone: form.value.phone,
            roleid: form.value.roleid,
            account: form.value.account,
            password: form.value.password,
            openid: ""
          }
        };
        apiService
          .post("", params)
          .then((res: any) => {
            // 使用 any 类型断言
            console.log(res.data);
            if (res.data.code == 200) {
              dialogVisible_add.value = false;
              form.value = [];
              message("新增完成", { type: "success" });
               GetList();
            } else if (res.data.code == 504) {
              message("用户已存在", { type: "warning" });
            }
          })
          .catch(error => {
            console.error("Error fetching data:", error);
          });
      }
    } else {
      console.log("错误输出！", fields);
    }
  });
};
//删除用户
const del = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "AdminDeleteUser",
        token: getToken().accessToken,
        seq: uuidv4(),
        body: {
          userid: row.Id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          GetList();
          ElMessage({
            type: "success",
            message: "删除成功"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const handleClose = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  ruleFormRef.value.clearValidate(); // 清除所有表单项的校验状态和错误信息
  form.value = [];
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

const type = ref<any>("");
onMounted(() => {
  GetList();
  // @ts-ignore

  const params = {
    msgid: "GetUserInfoByToken",
    token: getToken().accessToken,
    seq: uuidv4()
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log("用户详情", res.data);
      // @ts-ignore
      UserStore.type = res.data.body.name;
      // @ts-ignore
      if (UserStore.type == "超级管理员") {
        console.log("超级管理员");

        type.value = 1;
      } else {
        console.log("普通用户");
        type.value = 2;
      }
      //  console.log(UserStore.type);
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
});
</script>

<style lang="scss" scoped></style>
